package com.onlyphoto.onlymall.utils

import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.net.Uri
import com.onlyphoto.onlymall.MyApplication
import com.onlyphoto.onlymall.api.Api
import com.onlyphoto.onlymall.api.ApiService
import com.onlyphoto.onlymall.base.BaseNetworkResponse
import com.onlyphoto.onlymall.base.BaseObserver
import com.onlyphoto.onlymall.bean.FileBean
import com.onlyphoto.onlymall.events.UploadPicEvent
import com.onlyphoto.onlymall.interfaces.ProgressListener
import com.onlyphoto.onlymall.widget.AlertDialog
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import okhttp3.*

import org.greenrobot.eventbus.EventBus

import java.io.File


/**
 * Created by gaochujia on 2019-09-28.
 */

object FileUtil {

    private var myDisposable: CompositeDisposable? = null

    /************
     * 文件上传
     */
    @Throws(Exception::class)
    fun upLoadFile(serviceUrl: String?, bean: FileBean?, listener: ProgressListener, disposable: CompositeDisposable) {
        if (bean == null) {
            listener.onFailed(Exception("图片上传失败"))
            return
        }
        if (serviceUrl!!.trim { it <= ' ' }.isEmpty()) {
            listener.onFailed(Exception("图片上传失败"))
            return
        }
        val file = File(bean.fileSrc)
        if (!file.exists()) {
            listener.onFailed(Exception("图片文件不存在"))
            return
        }

        val builder = MultipartBody.Builder()
        builder.setType(MultipartBody.FORM)
        builder.addFormDataPart(bean.uploadKey!!, file.name, RequestBody.create(null, file))
        val set = bean.extraParams.entries
        val iterator = set.iterator()
        while (iterator.hasNext()) {
            val entry = iterator.next() as Map.Entry<*, *>
            builder.addFormDataPart(entry.key.toString(), entry.value.toString())
        }
        val requestBody = builder.build()
        myDisposable = disposable
        //开始请求
        Api.createApi().create(ApiService::class.java).upLoadPic(serviceUrl, requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe { mDisposable -> disposable.add(mDisposable) }
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : BaseObserver<Void>(MyApplication.app.getContext()){
                    override fun onSuccess(t: Void?, msg: String?) {
                        val event = UploadPicEvent()
                        event.pos = bean.pos
                        if (msg != null) {
                            listener.onSuccess(msg)
                            event.type = UploadPicEvent.UPLOAD_SUCCESS
                        }
                        EventBus.getDefault().post(event)

                    }

                    override fun onCodeError(t: BaseNetworkResponse<Void>?) {
                        val event = UploadPicEvent()
                        listener.onFailed(Exception("图片上传失败"))
                        event.type = UploadPicEvent.UPLOAD_FAILED
                        if (t != null) {
                            event.message = t.msg
                        } else {
                            event.message = "图片上传失败"
                        }
                        EventBus.getDefault().post(event)
                    }

                    override fun onFailure(e: Throwable?) {
                        listener.onFailed(Exception("图片上传失败"))
                        val event = UploadPicEvent()
                        event.pos = bean.pos
                        event.type = UploadPicEvent.UPLOAD_FAILED
                        event.message ="图片上传失败"
                        EventBus.getDefault().post(event)
                    }

                    override fun onRequestStart() {
                    }

                    override fun onFinally() {
                    }
                })
    }

    /************
     * 文件下载
     */
    /*fun downloadFile(serviceUrl: String, filePath: String, listener: BaseProgressListener?) {
        //开始请求
        Api.createApi().create(ApiService::class.java).downLoadPic(serviceUrl)
                .subscribe(object : BaseObserver<Response>(MyApplication.app.getContext()){
                    override fun onSuccess(t: Response?, msg: String?) {
                        try {
                            val filesize = t!!.body()!!.contentLength()
                            val `is` = t!!.body()!!.byteStream()
                            if (`is` == null || filesize == 0L) {
                                Log.d("tag", "网络文件不存在")
                                return
                            } else {
                                Log.d("tag", "网络文件存在")
                            }
                            val temp = File(filePath + ".downloading")
                            if (temp.exists()) {
                                temp.delete()
                            }
                            val os = FileOutputStream("$filePath.downloading")
                            val buff = ByteArray(1024)
                            val hasRead: Int = `is`.read(buff)
                            while (hasRead > 0) {
                                os.write(buff, 0, hasRead)
                            }
                            `is`.close()
                            os.close()
                            val downloadingFile = File("$filePath.downloading")
                            val downloadedFile = File(filePath)
                            if (downloadedFile.exists()) {
                                downloadedFile.delete()
                            }
                            downloadingFile.renameTo(File(filePath))
                            listener?.onSuccess( "下载成功")

                        } catch (e: IOException) {
                            listener?.onFailed(null)
                        }
                    }

                    override fun onCodeError(t: BaseNetworkResponse<Response>?) {
                    }

                    override fun onFailure(e: Throwable?) {
                        val downloadedFile = File(filePath)
                        if (downloadedFile.exists()) {
                            downloadedFile.delete()
                        }
                        listener?.onFailed(null)
                    }

                    override fun onRequestStart() {
                    }

                    override fun onFinally() {
                    }
                })
    }*/

    fun dispose(){
        if (myDisposable != null) {
            myDisposable!!.dispose()
            myDisposable!!.clear()
        }
    }

    fun installApk(file: File, context: Context) {

        try {
            val intent = Intent(Intent.ACTION_VIEW)
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            intent.setDataAndType(Uri.fromFile(file),
                    "application/vnd.android.package-archive")
            context.applicationContext.startActivity(intent)
        } catch (e: ActivityNotFoundException) {
            // TODO: handle exception
            AlertDialog(context).builder().setCancelable(false).setTitle("无法自动安装更新包").setMsg("请打开存储设备中kdkj/kdkj.apk文件安装")
                    .setNegativeButton("我知道了") { }.show()
        }

    }
}